package com.example.dangerouscargodriver.ui.activity;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.baiju.netmanager.Http.IHttpRequest;
import com.baiju.style.citylist.Toast.ToastUtils;
import com.baiju.utils.utils;
import com.example.dangerouscargodriver.controller.AuthController;
import com.example.dangerouscargodriver.controller.UserInfoController;
import com.example.dangerouscargodriver.entry.HandleRecordInfo;
import com.example.dangerouscargodriver.entry.ResourceDetailInfo;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.example.dangerouscargodriver.ui.fragment.home.HomeFragment;
import com.example.dangerouscargodriver.ui.view.QuotedPricePopupWindow;
import com.example.dangerouscargodriver.utils.DialogUtils;
import com.example.dangerouscargodriver.widget.ActionBar;
import com.example.dangerouscargodriver.R;
import com.example.dangerouscargodriver.widget.HandleRecordInfoView;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

public class ResourceDetailActivity extends HttpRequestActivity implements View.OnClickListener {

    private static final int MSG_GET_RESOURCE_INFO = 1;
    private static final String TAG = "ResourceDetailActivity";
    private static final int ACTION_LOGIN = 1;

    private ActionBar mActionBar = null;
    private TextView mQuotedPrice = null;
    private TextView mOrderNow = null;
    private ResourceDetailInfo mResourceInfo = null;
    private LinearLayout mTotalCostInfo = null;
    private LinearLayout mOnlineLayout = null;
    private LinearLayout mOfflineLayout = null;
    private TextView mPayType = null;
    private TextView mStartCity = null;
    private TextView mEndCity = null;

    private LinearLayout mMetaLayout = null;
    private TextView mRegTime = null;
    private TextView mMileage = null;
    private TextView mResourceWeight = null;
    private TextView mResourceType = null;

    private String mRecid = null;
    private TextView mExpectedPrice = null;
    private TextView mDeposit = null;
    private TextView mContact = null;
    private TextView mLoadTime = null;
    private TextView mRemark = null;
    private TextView mSourceNo = null;
    private TextView mCopyAction = null;
    private TextView mDepositReturn = null;
    private LinearLayout mLayoutContactOwner = null;

    private QuotedPricePopupWindow mPopupWindow = null;
    private String mUserQuotedPrice = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.initHttpComponent(ResourceDetailActivity.class);
        setContentView(R.layout.activity_resource_detail);

        mQuotedPrice = findViewById(R.id.btn_quoted_price);
        mQuotedPrice.setOnClickListener(this);
        mOrderNow = findViewById(R.id.btn_order_now);
        mOrderNow.setOnClickListener(this);
        //
        mRecid = getIntent().getStringExtra("recid");
        mRegTime = findViewById(R.id.tv_publish_time);
        mTotalCostInfo = findViewById(R.id.layout_total_cost_info);

        //!TODO:这里要根据用户信息来配置是否显示,此时用户未登录要如何进行处理？？？
        /*
        if(UserInfoController.Instance().getUserInfo().getIs_have_sg() == 1){
            mTotalCostInfo.setVisibility(View.GONE);
        }
         */

        mOnlineLayout = findViewById(R.id.layout_online_info);
        mOfflineLayout = findViewById(R.id.layout_offline_info);
        mPayType = findViewById(R.id.tv_pay_type);
        mMileage = findViewById(R.id.tv_mileage);
        mStartCity = findViewById(R.id.item_start_city);
        mEndCity = findViewById(R.id.item_end_city);
        mMetaLayout = findViewById(R.id.layout_resource_meta);
        mResourceType = findViewById(R.id.tv_resource_type);
        mResourceWeight = findViewById(R.id.tv_resource_weight);
        mExpectedPrice =findViewById(R.id.tv_expected_price);
        mDeposit = findViewById(R.id.tv_deposit);
        mContact = findViewById(R.id.tv_contact);
        mLoadTime = findViewById(R.id.tv_loadtime);
        mRemark = findViewById(R.id.tv_remark);
        mSourceNo = findViewById(R.id.tv_source_no);
        mCopyAction = findViewById(R.id.tv_copy_action);
        mCopyAction.setOnClickListener(this);
        mDepositReturn = findViewById(R.id.tv_deposit_return);

        if(UserInfoController.Instance().getUserInfo() != null &&
            UserInfoController.Instance().getUserInfo().getRole() != 1){
            mTotalCostInfo.setVisibility(View.VISIBLE);
        }
        else{
            mTotalCostInfo.setVisibility(View.GONE);
        }

        mLayoutContactOwner = findViewById(R.id.layout_contact_owner);

        mActionBar = findViewById(R.id.actionBarResourceDetail);
        mActionBar.setOnBackClickListener( new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                finish();
            }
        });

        executeGetResourceDetailInfo();
        executePlaceOrderCheck();
    }

    private void executeGetResourceDetailInfo() {
        sendHttpRequest(IHttpRequest.RequestMethod.GET_METHOD,
            RemoteAPI.REQUEST_V1_HOME_SEARCH_SOURCE_GOODS+ "/" + mRecid,
            null,
            null,
            RemoteAPICmd.REQUEST_V1_HOME_RECID_SEARCH_SOURCE_GOODS);
    }

    private void executePlaceOrderCheck(){
        if(!AuthController.Instance().checkLogin()){
            return;
        }
        HashMap<String, String> header = new HashMap<>();
        header.put("token", AuthController.Instance().getToken());

        sendHttpRequest(IHttpRequest.RequestMethod.GET_METHOD,
                RemoteAPI.REQUEST_V1_PLACE_ORDER_CHECK,
                header,
                null,
                RemoteAPICmd.REQUEST_V1_PLACE_ORDER_CHECK);
    }

    private void refreshViewContent() {
        mRegTime.setText(mResourceInfo.getRegtime());
        mExpectedPrice.setText(mResourceInfo.getExpected_price());
        mDeposit.setText(mResourceInfo.getDeposit());
        if(mResourceInfo.getPay_type().equals("2")){
            mDepositReturn.setVisibility(View.GONE);
        }
        else{
            mDepositReturn.setVisibility(View.VISIBLE);
        }
        mContact.setText(mResourceInfo.getContact());
        if(mResourceInfo.getLoadtime2() != null){
            mLoadTime.setText(mResourceInfo.getLoadtime() + "-" + mResourceInfo.getLoadtime2());
        }
        else{
            mLoadTime.setText(mResourceInfo.getLoadtime());
        }
        mRemark.setText(mResourceInfo.getRemark());
        mSourceNo.setText(mResourceInfo.getSource_no());

        if(mResourceInfo.getPay_type().equals("1")){
            mOnlineLayout.setVisibility(View.GONE);
            mOfflineLayout.setVisibility(View.VISIBLE);
            mPayType.setText(R.string.item_pay_offline);
        }
        else{
            mOnlineLayout.setVisibility(View.VISIBLE);
            mOfflineLayout.setVisibility(View.GONE);
            mPayType.setText(R.string.item_pay_online);
        }
        Log.d(TAG, "getFrom_name: " + mResourceInfo.getFrom_name());
        mStartCity.setText(mResourceInfo.getFrom_name());
        mEndCity.setText(mResourceInfo.getTo_name());
        if(mResourceInfo.getName() != null && !mResourceInfo.getName().equals("")){
            View layout = LayoutInflater.from(getBaseContext()).inflate(R.layout.layout_resource_meta_info_item, null);
            TextView textView = layout.findViewById(R.id.tv_item_meta_string);
            textView.setText(mResourceInfo.getName());
            mMetaLayout.addView(layout);
        }
        if(mResourceInfo.getClassname() != null && !mResourceInfo.getClassname().equals("")){
            View layout = LayoutInflater.from(getBaseContext()).inflate(R.layout.layout_resource_meta_info_item, null);
            TextView textView = layout.findViewById(R.id.tv_item_meta_string);
            textView.setText(mResourceInfo.getClassname());
            mMetaLayout.addView(layout);
        }
        if(mResourceInfo.getWeight() != null && !mResourceInfo.getWeight().equals("")){
            View layout = LayoutInflater.from(getBaseContext()).inflate(R.layout.layout_resource_meta_info_item, null);
            TextView textView = layout.findViewById(R.id.tv_item_meta_string);
            textView.setText(mResourceInfo.getWeight() + "吨");
            mMetaLayout.addView(layout);
        }
        if(mResourceInfo.getTruck_type() != null && !mResourceInfo.getTruck_type().equals("")){
            String truckType = mResourceInfo.getTruck_type();
            String[] truckTypeArray = truckType.split(",");

            for(int index = 0; index < truckTypeArray.length; index++){
                View layout = LayoutInflater.from(getBaseContext()).inflate(R.layout.layout_resource_meta_info_item, null);
                TextView textView = layout.findViewById(R.id.tv_item_meta_string);
                textView.setText(truckTypeArray[index]);
                mMetaLayout.addView(layout);
            }
        }
        mMileage.setText(mResourceInfo.getSource_distance());
        mResourceType.setText(mResourceInfo.getClassname());
        mResourceWeight.setText(mResourceInfo.getWeight());
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btn_quoted_price){
            if(AuthController.Instance().checkLogin()) {
                if(UserInfoController.Instance().getUserInfo().getRole() == 2 ||
                        UserInfoController.Instance().getUserInfo().getRole() == 3) {
                    if (mPopupWindow == null) {
                        mPopupWindow = new QuotedPricePopupWindow(this);
                    }
                    mPopupWindow.setPrice(Float.parseFloat(mResourceInfo.getExpected_price()));
                    mPopupWindow.setInputListener(new QuotedPricePopupWindow.onInputListener() {
                        @Override
                        public void onInput(String price) {
                            mUserQuotedPrice = price;
                            mExpectedPrice.setText(mUserQuotedPrice);
                        }
                    });
                    mPopupWindow.showPopupWindow(true);
                }
                else {
                    DialogUtils.showAlertDialog(this,
                            getResources().getString(R.string.title_choose_enter_role),
                            getResources().getString(R.string.title_choose_enter_role_meta),
                            getResources().getString(R.string.text_enter_company),
                            getResources().getString(R.string.text_enter_personal),
                            true,
                            new DialogUtils.AlertDialogBtnClickListener() {
                                @Override
                                public void clickPositive() {
                                    //negative
                                    Intent intent = new Intent(ResourceDetailActivity.this, EnterPlatformCompanyStepOneActivity.class);
                                    startActivity(intent);
                                }
                                @Override
                                public void clickNegative() {
                                    //positive
                                    Intent intent = new Intent(ResourceDetailActivity.this, EnterPlatformPersonalStepOneActivity.class);
                                    startActivity(intent);
                                }
                            });
                }
            }
            else{
                Intent intent = new Intent(this, LogInActivity.class);
                startActivityForResult(intent, ACTION_LOGIN);
            }
        }
        else if(v.getId() == R.id.btn_order_now){
            if(AuthController.Instance().checkLogin()) {
                if(UserInfoController.Instance().getUserInfo().getRole() == 2 ||
                        UserInfoController.Instance().getUserInfo().getRole() == 3) {
                    Intent intent = new Intent(this, OrderNowActivity.class);
                    if (mUserQuotedPrice != null) {
                        mResourceInfo.setExpected_price(mUserQuotedPrice);
                    }
                    intent.putExtra("info", mResourceInfo);
                    startActivity(intent);
                }
                else {
                    DialogUtils.showAlertDialog(this,
                            getResources().getString(R.string.title_choose_enter_role),
                            getResources().getString(R.string.title_choose_enter_role_meta),
                            getResources().getString(R.string.text_enter_company),
                            getResources().getString(R.string.text_enter_personal),
                            true,
                            new DialogUtils.AlertDialogBtnClickListener() {
                                @Override
                                public void clickPositive() {
                                    //negative
                                    Intent intent = new Intent(ResourceDetailActivity.this, EnterPlatformCompanyStepOneActivity.class);
                                    startActivity(intent);
                                }
                                @Override
                                public void clickNegative() {
                                    //positive
                                    Intent intent = new Intent(ResourceDetailActivity.this, EnterPlatformPersonalStepOneActivity.class);
                                    startActivity(intent);
                                }
                            });
                }
            }
            else{
                Intent intent = new Intent(this, LogInActivity.class);
                startActivityForResult(intent, ACTION_LOGIN);
            }
        }
        else if(v.getId() == R.id.tv_copy_action){
            ToastUtils.showLongToast(getBaseContext(), "已复制到剪贴板!");
            //获取剪贴板管理器：
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                ClipboardManager cm = null;
                cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建普通字符型ClipData
                ClipData mClipData = ClipData.newPlainText("Label", mSourceNo.getText());
                // 将ClipData内容放到系统剪贴板里。
                cm.setPrimaryClip(mClipData);
            }
            else{
                // 从API11开始android推荐使用android.content.ClipboardManager
                // 为了兼容低版本我们这里使用旧版的android.text.ClipboardManager，虽然提示deprecated，但不影响使用。
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // 将文本内容放到系统剪贴板里。
                cm.setText(mSourceNo.getText());
            }
        }
        else{
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onHttpResponse(int actionId, String response) {
        try {
            JSONObject res = new JSONObject(response);
            Gson gson = new Gson();
            Log.d(TAG, "onResponse: " + response);

            if(actionId == RemoteAPICmd.REQUEST_V1_HOME_RECID_SEARCH_SOURCE_GOODS){
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    JSONObject data = res.getJSONObject("data");
                    mResourceInfo = gson.fromJson(data.toString(), ResourceDetailInfo.class);

                    Log.d(TAG, "mResourceInfo: " + mResourceInfo.toString());

                    refreshViewContent();
                }
            }
            else if(actionId == RemoteAPICmd.REQUEST_V1_PLACE_ORDER_CHECK){
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    JSONObject data = res.getJSONObject("data");
                    if(!data.get("role").equals("1")){
                        mLayoutContactOwner.setVisibility(View.VISIBLE);
                    }
                }
            }
            else{

            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onHttpErrorResponse(int actionId, String response) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //此处可以根据两个Code进行判断，本页面和结果页面跳过来的值
        if (requestCode == ACTION_LOGIN) {
            /**/
        }
        else {
            /**/
        }
    }
}